package com.blog.distribute.exception;


import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.blog.common.CommonRespDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;


import java.io.PrintWriter;

/**
 * @ClassName MySentinelExceptionHandler
 * @Destription 自定义 web接口sentinel异常处理-BlockException
 * @Author 天堂小野花
 * @Date 2025/8/5  20:58
 * @Version 1.0
 */
@Component
public class MySentinelExceptionHandler implements BlockExceptionHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();


        CommonRespDto error = CommonRespDto.error("500", "来自自定义Sentinel异常处理："+e.getClass());

        String json = objectMapper.writeValueAsString(error);
        writer.write(json);
        writer.flush();
        writer.close();
    }

}
